<?php

namespace app\index\controller;

use app\common\JwtHelper;
use app\index\job\JobOrder;
use app\middleware\SecurityMiddleware;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;
use uploadImg\imgcompress;

class Api extends Controller
{
    public function __construct()
    {
        parent::__construct();

        // 调用中间件
        $middleware = new SecurityMiddleware();
        $request = Request::instance();
        $middleware->handle($request, function ($req) {
            // 仅执行验证，不做中间件链路回调
            return response(); // 返回空响应对象用于中间件添加响应头
        });
    }

    public static function authorizationGetOpenid()
    {
        $request = request(); // 获取当前请求

        $authHeader = $request->header('authorization', '');

        if ($authHeader && stripos($authHeader, 'Bearer ') === 0) {
            $token = substr($authHeader, 7);
            $payload = JwtHelper::verifyToken($token);

            if ($payload && !empty($payload['openid'])) {
                // 可选：自动续期（设置响应头，供中间件读取）
                if (JwtHelper::shouldRefreshToken($payload)) {
                    $newToken = JwtHelper::createToken(['openid' => $payload['openid']]);
                    header('X-Refreshed-Token: ' . $newToken);
                }
            }
        }
        return $payload['openid'] ? : '';
    }

    public function codeGetOpenidToUserInfo()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, 'code缺失');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $user_data = json_decode(file_get_contents($url));

        $openid = $user_data->openid;

        $user_info = Db::name('user')->field('id,username,avatar')->where(['openid' => $openid])->find();
        if ($user_info) {
            $user_info['avatar'] = $user_info['avatar'] ? doAvatar($user_info['avatar']) : '/images/avatar.png';

            apiReturn(1, '获取用户信息成功', $user_info);
        } else {
            apiReturn(2, '获取用户信息失败');
        }
    }

    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $json_res = httpsRequest($url);
        $user_data = json_decode($json_res);

        if ($openid = $user_data->openid) {
            apiReturn(1, '获取数据成功', $openid);
        } else {
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = getAccessToken();
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        file_put_contents(RUNTIME_PATH . 'error.json', json_encode($input, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        file_put_contents(RUNTIME_PATH . 'error.json', $result . PHP_EOL . PHP_EOL, FILE_APPEND);
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                apiReturn(1, '获取数据成功', $mobile);
            } else {
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();

        $openid = $input['openid'];
        $avatar = $input['avatar'];
        $nickname = $input['nickname'];
        $mobile = $input['mobile'];
        //        $share_user_id = $input['share_user_id'] ? : 0;
        //        $style = $input['style'] ? : 1;// 1：渠道商发展业务员，2：业务员发展供应商

        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($avatar)) apiReturn(2, '请上传头像信息');
        if (empty($nickname)) apiReturn(2, '请填写昵称');
        if (empty($mobile)) apiReturn(2, '请获取手机号');

        $mobile_count = Db::name('user')->where(['mobile' => $mobile])->count();
        if ($mobile_count > 0) apiReturn(2, '该手机号已使用');

        Db::startTrans();
        try {
            $count = Db::name('user')->where(['openid' => $openid])->count();
            if ($count == 0) {
                $data = [
                    'openid' => $openid,
                    'avatar' => str_replace(getHost(), '', $avatar),
                    'username' => $nickname,
                    'mobile' => $mobile,
                    'create_time' => time()
                ];

                // 绑定关系数据
                //                $bind_data = bindUserUp($share_user_id, $style);
                //                if ($bind_data) $data = array_merge($data, $bind_data);

                $insert_user_id = Db::name('user')->insertGetId($data);
                if (!$insert_user_id) {
                    Db::rollback();
                    apiReturn(2, '系统繁忙，请稍后再试~');
                }
            }

            Db::commit();

            $token = JwtHelper::createToken(['openid' => $openid]);
            apiReturn(1, '登录成功', $token);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    public function bindUser()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户不存在');

        $input = Request()->param();

        $share_user_id = $input['share_user_id'];
        $style = $input['style'];//1：渠道商发展业务员， 2：业务员发展供应商

        if (!$share_user_id || !$style) apiReturn(2, '参数缺失');

        $bind_data = bindUserUp($share_user_id, $style);
        if ($bind_data) {
            if (($style == 1 && $user_info['up_channel_user_id'] > 0) || ($style == 2 && $user_info['up_salesman_user_id'] > 0)) apiReturn(2, '您已绑定过关系');

            Db::startTrans();
            try {
                $res = Db::name('user')->where(['id' => $user_id])->update($bind_data);
                if (!$res) {
                    Db::rollback();
                    apiReturn(2, '绑定失败');
                }

                if ($style == 1) {
                    $salesman_ident_info = Db::name('user_ident')->where(['id' => $user_info['salesman_id']])->find();
                    if ($salesman_ident_info['status'] == 1) {
                        // 认证审核已经通过了，直接将上级渠道商发展人数+1
                        $res = Db::name('user')->where(['id' => $share_user_id])->setInc('son_salesman_count');
                        if (!$res) {
                            Db::rollback();
                            apiReturn(2, '绑定失败');
                        }
                    }
                } elseif ($style == 2) {
                    $supplier_ident_info = Db::name('user_ident')->where(['id' => $user_info['supplier_id']])->find();
                    if ($supplier_ident_info['status'] == 1) {
                        // 认证审核已经通过了，直接将上级业务员发展供应商人数+1，评分增加
                        $salesman_user_info = Db::name('user')->field('son_supplier_count,salesman_score,salesman_id')->where(['id' => $share_user_id])->find();
                        if ($salesman_user_info) {
                            $res = Db::name('user')->where(['id' => $share_user_id])->setInc('son_supplier_count');
                            if (!$res) {
                                Db::rollback();
                                apiReturn(2, '绑定失败');
                            }

                            $salesman_share_score = C('SALESMAN_SHARE_SCORE');
                            if ($salesman_user_info['salesman_id'] && $salesman_share_score > 0) {
                                $up_salesman_ident_info = Db::name('user_ident')->where(['id' => $salesman_user_info['salesman_id']])->find();
                                doScore($share_user_id, $up_salesman_ident_info['id'], 'salesman_score', $salesman_share_score, 'share_register', $user_id, 'pu_user', '业务员拉新奖励');
                            }
                        }
                    }
                }

                Db::commit();
                apiReturn(1, '绑定成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '绑定失败' . $e->getMessage());
            }
        } else {
            apiReturn(2, '绑定失败');
        }
    }

    /**
     * 获取token
     * */
    public function getLoginToken()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(httpsRequest($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, '登录失败');

        $user_info = Db::name('user')->where('openid', $openid)->find();
        if ($user_info) {
            $token = JwtHelper::createToken(['openid' => $openid]);
            apiReturn(1, '登录成功', $token);
        } else {
            apiReturn(2, '新用户，走注册流程');
        }
    }

    /**
     * 个人中心
     * */
    public function userCenter()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,username,avatar,mobile,supplier_id,integral,channel_id,channel_score,salesman_id,salesman_score,son_salesman_count,son_supplier_count')->where(['openid' => $openid])->find();

        $info['avatar'] = $info['avatar'] ? getHost() . $info['avatar'] : '/static/images/avatar.png';
        $info['hide_mobile'] = $info['mobile'] ? hideMobile($info['mobile']) : '';

        // 供应商服务申请数量
        $supplier_apply_service_count = 0;

        if ($info['supplier_id'] > 0) {
            $supplier_apply_service_count = Db::name('order')->where(['user_id' => $info['id'], 'status' => ['neq', -1]])->count();
            $supplier_status = Db::name('user_ident')->where(['id' => $info['supplier_id']])->value('status');
        }
        $info['supplier_status'] = $supplier_status ? : 0;

        $info['supplier_apply_service_count'] = $supplier_apply_service_count;

        if ($channel_id = $info['channel_id']) {
            $channel_status = Db::name('user_ident')->where(['id' => $channel_id])->value('status');
        }
        $info['channel_status'] = $channel_status ? : 0;

        if ($salesman_id = $info['salesman_id']) {
            $salesman_status = Db::name('user_ident')->where(['id' => $salesman_id])->value('status');
        }
        $info['salesman_status'] = $salesman_status ? : 0;

        $info['channel_qr'] = createChannelQr($info['id']);
        $info['salesman_qr'] = createSalesmanQr($info['id']);

        $work_time = array_values(array_filter(C('WORK_TIME')));
        $info['work_time'] = $work_time;

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 生成渠道商二维码
     * */
    public function createChannelQr()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $qr = createChannelQr($user_id);
        if ($qr) {
            apiReturn(1, '生成成功', $qr);
        } else {
            apiReturn(2, '生成推广码失败');
        }
    }

    /**
     * 生成业务员二维码
     * */
    public function createSalesmanQr()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $qr = createSalesmanQr($user_id);
        if ($qr) {
            apiReturn(1, '生成成功', $qr);
        } else {
            apiReturn(2, '生成推广码失败');
        }
    }

    /**
     * 积分明细
     * */
    public function integralList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('user_integral_log')->field('id,integral,remark,create_time')->where(['user_id' => $user_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = formatRelativeTime($v['create_time']);
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 评分明细
     * */
    public function scoreList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;
        $type = $input['type'] ? : 2;// 2：渠道商，3：业务员

        if ($type == 2) {
            $ident_id = Db::name('user')->where(['id' => $user_id])->value('channel_id');
        } else {
            $ident_id = Db::name('user')->where(['id' => $user_id])->value('salesman_id');
        }

        if ($ident_id) {
            $list = Db::name('user_score_log')->field('id,score,remark,create_time')->where(['ident_id' => $ident_id])->order('id desc')->page($page, $pagesize)->select();
            if ($list) {
                foreach ($list as &$v) {
                    $v['create_time'] = formatRelativeTime($v['create_time']);
                }
                apiReturn(1, '获取数据成功', $list);
            } else {
                apiReturn(2, '暂无更多数据');
            }
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 供应商订单列表
     * */
    public function supplierOrderList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['status'] = ['neq', -1];
        $where['user_id'] = $user_id;
        if ($status) $where['status'] = $status;

        $list = Db::name('order')->field('id,service_id,service_name,channel_user_id,status,create_time')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i');
                $v['status_desc'] = doOrderStatus($v['status']);

                $channel_info = Db::name('user_ident')->field('username,mobile')->where(['user_id' => $v['channel_user_id'], 'type' => 2])->find();
                $v['channel_username'] = $channel_info['username'] ? : '';
                $v['channel_mobile'] = $channel_info['mobile'] ? : '';
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 供应商订单详情
     * */
    public function supplierOrderDetail()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();
        $id = $input['id'];

        if (empty($id)) apiReturn(2, '参数错误');

        $info = Db::name('order')->field('id,order_sn,service_name,channel_user_id,score,status,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['create_time'] = timeFormat($info['create_time'], 'Y-m-d H:i');
            $info['score_desc'] = doScoreDesc($info['score']);

            if ($channel_user_id = $info['channel_user_id']) {
                $channel_info = Db::name('user_ident')->where(['user_id' => $channel_user_id])->find();
                $channel_company_name = $channel_info['company_name'];
                $channel_username = $channel_info['username'];
                $channel_mobile = $channel_info['mobile'];
            }

            $info['channel_company_name'] = $channel_company_name ? : '';
            $info['channel_username'] = $channel_username ? : '';
            $info['channel_mobile'] = $channel_mobile ? : '';

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 评分
     * */
    public function comment()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $id = $input['id'];
        $score = $input['score'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if (!in_array($score, [-1, 1, 2, 3])) apiReturn(2, '评分异常');

        $info = Db::name('order')->where(['id' => $id])->find();
        if (empty($info)) apiReturn(2, '订单不存在');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在');

        if ($channel_user_id = $info['channel_user_id']) {
            $channel_user_info = Db::name('user')->where(['id' => $channel_user_id])->find();
            if (empty($channel_user_info)) apiReturn(2, '渠道商信息不存在');
        }

        if ($service_id = $info['service_id']) {
            $service_info = Db::name('service')->where(['id' => $service_id])->find();
            if (empty($service_info)) apiReturn(2, '服务信息不存在');
        }

        Db::startTrans();
        try {
            $time = time();
            $data = [
                'score' => $score,
                'status' => 3,
                'comment_time' => $time
            ];

            // 修改订单数据
            $res = Db::name('order')->where(['id' => $id])->update($data);
            if (!$res) {
                Db::rollback();
                apiReturn(2, '评分失败');
            }

            // 操作渠道商评分
            $remark = '完成一项服务，服务ID：' . $info['service_id'] . '；【' . $info['service_name'] . '】完成获得评分';
            $res = doScore($channel_user_id, $channel_user_info['channel_id'], 'channel_score', $score, 'comment', $info['id'], 'pu_order', $remark);
            if (!$res) {
                Db::rollback();
                apiReturn(2, '评分失败');
            }

            $type_integral = Db::name('service_type')->where(['id' => $service_info['type_id']])->value('integral');
            if ($type_integral) {
                // 操作渠道商用户积分
                $res = doIntegral($channel_user_id, $type_integral, 'channel_complete', $id, 'pu_order', '渠道商完成服务交付');
                if (!$res) {
                    Db::rollback();
                    apiReturn(2, '评分失败');
                }
            }

            $comment_score_integral = C('COMMENT_SCORE_INTEGRAL');
            if ($comment_score_integral > 0 || $type_integral > 0) {
                // 操作供应商积分
                $supplier_remark = '';
                if ($comment_score_integral) $supplier_remark .= '主动评价+' . $comment_score_integral . '积分';
                if ($type_integral) $supplier_remark .= '，完成交易+' . $type_integral . '积分';
                $res = doIntegral($user_id, $comment_score_integral + $type_integral, 'supplier_comment_complete', $id, 'pu_order', $supplier_remark);
                if (!$res) {
                    Db::rollback();
                    apiReturn(2, '评分失败');
                }
            }

            $salesman_share_integral = C('SALESMAN_SHARE_INTEGRAL');
            if ($user_info['supplier_first_order'] == 0 && $user_info['up_salesman_user_id'] > 0 && $salesman_share_integral > 0) {
                // 拉新完成首单，业务员奖励积分
                $res = doIntegral($user_info['up_salesman_user_id'], $salesman_share_integral, 'share_register', $id, 'pu_order', '拉新完成首单');
                if (!$res) {
                    Db::rollback();
                    apiReturn(2, '评分失败');
                }

                // 更新用户首单状态
                $res = Db::name('user')->where(['id' => $user_id])->setField('supplier_first_order', 1);
                if (!$res) {
                    Db::rollback();
                    apiReturn(2, '评分失败');
                }
            }

            // 服务修改评分
            $res = Db::name('service')->where(['id' => $info['service_id']])->setField('score', $service_info['score'] + $score);
            if (!$res) {
                Db::rollback();
                apiReturn(2, '评分失败');
            }

            // 真实服务人数+1
            $res = Db::name('service')->where(['id' => $info['service_id']])->setInc('count');
            if (!$res) {
                Db::rollback();
                apiReturn(2, '评分失败');
            }

            Db::commit();
            apiReturn(1, '评分成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '评分失败');
        }
    }

    /**
     * 渠道商订单列表
     * */
    public function channelOrderList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['status'] = ['neq', -1];
        $where['channel_user_id'] = $user_id;
        if ($status) $where['status'] = $status;

        $list = Db::name('order')->field('id,service_id,service_name,user_id,status,create_time')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i');
                $v['status_desc'] = doOrderStatus($v['status']);

                $supplier_info = Db::name('user_ident')->field('username,mobile')->where(['user_id' => $v['user_id'], 'type' => 1])->find();
                $v['supplier_username'] = $supplier_info['username'] ? : '';
                $v['supplier_mobile'] = $supplier_info['mobile'] ? : '';
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 渠道商订单详情
     * */
    public function channelOrderDetail()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();
        $id = $input['id'];

        if (empty($id)) apiReturn(2, '参数错误');

        $info = Db::name('order')->field('id,order_sn,service_name,user_id,score,status,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['create_time'] = timeFormat($info['create_time'], 'Y-m-d H:i');
            $info['score_desc'] = doScoreDesc($info['score']);

            if ($user_id = $info['user_id']) {
                $ident_info = Db::name('user_ident')->where(['user_id' => $user_id])->find();
                $company_name = $ident_info['company_name'];
                $username = $ident_info['username'];
                $mobile = $ident_info['mobile'];
            }

            $info['company_name'] = $company_name ? : '';
            $info['username'] = $username ? : '';
            $info['mobile'] = $mobile ? : '';

            if ($info['is_accept'] == 0) {
                // 将订单修改未已接单状态
                Db::name('order')->where(['id' => $id])->setField('is_accept', 1);
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    public function test()
    {
        createSalesmanQr(58);
    }

    /**
     * 获取认证信息
     * */
    public function getIdentInfo()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录1');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $type = $input['type'] ? : 1;// 1：供应商，2：渠道商，3：业务员

        $where = [
            'user_id' => $user_id,
            'type' => $type
        ];

        $info = Db::name('user_ident')->where($where)->find();
        if (empty($info) && $type != 3) {
            $where['type'] = ['IN', [1, 2]];
            $info = Db::name('user_ident')->where($where)->find();
            if ($info) {
                $info['id'] = 0;
                $info['status'] = 0;
            }
        }
        if ($info) {
            if ($info['yyzz_img']) $info['yyzz_img'] = getHost() . $info['yyzz_img'];

            switch ($info['status']) {
                case 1:
                    $info['status_desc'] = '已通过';
                    break;
                case 2:
                    $info['status_desc'] = '已驳回';
                    break;
                default:
                    $info['status_desc'] = '审核中';
                    break;
            }

            if ($type == 3) {
                // 所属企业名称
                $up_channel_user_id = Db::name('user')->where(['id' => $info['user_id']])->value('up_channel_user_id');
                if ($up_channel_user_id) {
                    $info['up_company_name'] = Db::name('user_ident')->where(['user_id' => $up_channel_user_id, 'type' => 2])->value('company_name');
                }
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(1, '未认证');
        }
    }

    /**
     * 首页搜索关键词
     * */
    public function indexSearchKeywords()
    {
        $keywords = array_values(array_filter(C('INDEX_SEARCH_KEYWORDS')));

        apiReturn(1, '获取数据成功', $keywords);
    }

    /**
     * 快捷入口
     * */
    public function serviceQuickList()
    {
        $list = Db::name('service_quick')->field('id,name,img,service_id')->order('sort asc')->limit(5)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = $v['img'] ? getHost() . $v['img'] : '';
            }
        }
        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 采集分类
     * */
    public function gatherTypeList()
    {
        $list = Db::name('gather_type')->field('id,name')->where(['pid' => 0, 'is_show' => 1])->select();
        if ($list) {
            foreach ($list as &$v) {
                $son_list = Db::name('gather_type')->field('id,name')->where(['pid' => $v['id'], 'is_show' => 1])->order('id asc')->select();
                $v['son_list'] = $son_list ? : [];

                if (in_array($v['id'], [14, 15, 16, 17, 18, 19, 20, 21])) {
                    // 【国有资源】接口
                    $v['api_name'] = 'gatherResourceList';
                } elseif ($v['id'] == 13) {
                    // 医药采购
                    $v['api_name'] = 'gatherMedicineList';
                } elseif ($v['id'] == 22) {
                    // 国有资产
                    $v['api_name'] = 'gatherPropertyList';
                } elseif ($v['id'] == 23) {
                    // 环境权
                    $v['api_name'] = 'gatherEnvironmentList';
                } else {
                    // 【工程建设、政府采购、其他交易】接口
                    $v['api_name'] = 'gatherList';
                }

            }
        }
        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 工程建设、政府采购、其他交易
     * */
    public function gatherList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'] ? : 0;
        $two_type_id = $input['two_type_id'] ? : 0;
        $search_value = $input['search_value'] ? : '';
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;
        $offset = ($page - 1) * $pagesize;

        $where = "is_gather = 1";
        if ($one_type_id > 0) $where .= " AND one_type_id = {$one_type_id}";
        if ($two_type_id > 0) $where .= " AND two_type_id = {$two_type_id}";

        if ($search_value) {
            // 把搜索词以空格拆分，拼成 +词 +词 形式
            $words = preg_split('/\s+/', trim($search_value));
            $boolKeyword = '+' . implode(' +', $words);

            $where .= " AND MATCH(title) AGAINST(:keyword IN BOOLEAN MODE)";
            $sql = "
                SELECT id, title, `from`, publish_time
                FROM pu_gather
                WHERE {$where}
                ORDER BY publish_time DESC
                LIMIT {$offset}, {$pagesize}
            ";
            $list = Db::query($sql, ['keyword' => $boolKeyword]);
        } else {
            // 非全文搜索时，继续使用 TP5 ORM 查询构建器
            $where_arr = ['is_gather' => 1];
            if ($one_type_id > 0) $where_arr['one_type_id'] = $one_type_id;
            if ($two_type_id > 0) $where_arr['two_type_id'] = $two_type_id;

            $list = Db::name('gather')
                ->field('id,title,from,publish_time')
                ->where($where_arr)
                ->order('publish_time desc')
                ->limit($offset, $pagesize)
                ->select();
        }
        if ($list) {
            foreach ($list as &$v) {
                $v['publish_time'] = $v['publish_time'] ? date('Y-m-d H:i', strtotime($v['publish_time'])) : '';
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 详情（工程建设、政府采购、其他交易）
     * */
    public function gatherDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, 'ID缺失');

        $info = Db::name('gather')->field('id,title,one_type_id,two_type_id,from,publish_time,content,content_json')->where(['id' => $id])->find();

        $info['publish_time'] = $info['publish_time'] ? date('Y-m-d', strtotime($info['publish_time'])) : '';
        if ($info['one_type_id'] == 27) {
            $info['content'] = formatRichTextForWechatMiniProgram($info['content']);
        } else {
            $info['content_json'] = json_decode($info['content_json'], true);
        }

        if ($info) {
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '数据不存在');
        }
    }

    /**
     * 医药采购列表
     * */
    public function gatherMedicineList()
    {
        $input = Request()->param();

        $search_value = $input['search_value'] ? : '';
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where = [];
        if ($search_value) $where['title'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_medicine')->field('id,title,publish_time')->where($where)->order('publish_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['publish_time'] = date('Y-m-d', strtotime($v['publish_time']));
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 国有资源
     * */
    public function gatherResourceList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'] ? : 0;
        $two_type_id = $input['two_type_id'] ? : 0;
        $search_value = $input['search_value'] ? : '';
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where = [];
        if ($one_type_id > 0) $where['one_type_id'] = $one_type_id;
        if ($two_type_id > 0) {
            $where['two_type_id'] = $two_type_id != 19 ? $two_type_id : ["IN", [19, 28]];
        }
        if ($search_value) $where['landName|resourceName'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_resource')->where($where)->order('publish_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                if (in_array($v['two_type_id'], [15, 16])) {
                    $render_data = [
                        ['label' => '宗地编号', 'value' => $v['projectName']],
                        ['label' => '宗地名称', 'value' => $v['resourceName']],
                        ['label' => '挂牌时间', 'value' => $v['listStartTime'] . ' 至 ' . $v['listEndTime']],
                        ['label' => '保证金', 'value' => number_format($v['amountReceived']) . '万元'],
                        ['label' => '保证金到账截止时间', 'value' => $v['depositEndTime']],
                        ['label' => '起始价', 'value' => number_format($v['initQuote']) . '万元'],
                        ['label' => '资源位置', 'value' => $v['landLocation']]
                    ];
                } elseif (in_array($v['two_type_id'], [17, 18, 21])) {
                    $render_data = [
                        ['label' => '挂牌时间', 'value' => $v['listStartTime'] . ' 至 ' . $v['listEndTime']],
                        ['label' => '保证金', 'value' => number_format($v['amountReceived']) . '万元'],
                        ['label' => '保证金到账截止时间', 'value' => $v['depositEndTime']],
                        ['label' => '起始价', 'value' => number_format($v['initQuote']) . '万元'],
                    ];
                } elseif (in_array($v['two_type_id'], [19, 28])) {
                    $render_data = [
                        ['label' => '挂牌时间', 'value' => $v['listStartTime'] . ' 至 ' . $v['listEndTime']],
                        ['label' => '探矿权名称', 'value' => $v['resourceName']],
                        ['label' => '保证金到账截止时间', 'value' => $v['depositEndTime']],
                        ['label' => '保证金', 'value' => number_format($v['amountReceived']) . '万元'],
                        ['label' => '资源位置', 'value' => $v['landLocation']],
                        ['label' => '起始价', 'value' => number_format($v['initQuote']) . '万元']
                    ];
                }
                $v['render_data'] = $render_data;

                $v['quote_num'] = '';
                if ($v['highestQuote']) {
                    $highestQuote = json_decode($v['highestQuote'], true);
                    $v['quote_num'] = number_format($highestQuote['quote_num']) . '万元';
                }
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 国有资产
     * */
    public function gatherPropertyList()
    {
        $input = Request()->param();

        $search_value = $input['search_value'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if ($search_value) {
            $where['markName'] = ['LIKE', "%$search_value%"];
        } else {
            $where['markName'] = ['NOT NULL', ''];
        }

        $list = Db::name('gather_property')->field('id,markName,processNo,depositNeedPay,initQuote,applyStartTime,applyEndTime')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['depositNeedPay'] = number_format($v['depositNeedPay']) . '万元';
                $v['initQuote'] = number_format($v['initQuote']) . '万元';
                $v['applyStartTime'] = date('Y-m-d H:i', strtotime($v['applyStartTime']));
                $v['applyEndTime'] = date('Y-m-d H:i', strtotime($v['applyEndTime']));
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 环境权
     * */
    public function gatherEnvironmentList()
    {
        $input = Request()->param();

        $search_value = $input['search_value'] ? : '';
        $one_type_id = $input['one_type_id'] ? : 0;
        $two_type_id = $input['two_type_id'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where = [];
        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($two_type_id) $where['two_type_id'] = $two_type_id;

        if ($search_value) $where['processNo'] = ['LIKE', "%$search_value%"];

        $list = Db::name('gather_environment')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['listStartTime'] = $v['listStartTime'] ? date('Y-m-d H:i', strtotime($v['listStartTime'])) : '';
                $v['listEndTime'] = $v['listEndTime'] ? date('Y-m-d H:i', strtotime($v['listEndTime'])) : '';

                $v['quoteUnit'] = $v['quoteUnitName'] ? : doQuoteUnit($v['quoteUnit']);

                $v['initQuote'] = $v['initQuote'] ? number_format($v['initQuote']) : 0;
                $v['quoteRange'] = $v['quoteRange'] ? number_format($v['quoteRange']) : 0;

                $topQuoteNum = json_encode($v['topQuoteNum'], JSON_UNESCAPED_UNICODE);
                if ($topQuoteNum) {
                    $high = number_format($topQuoteNum['quote_num']) . doQuoteUnit($topQuoteNum['quote_unit']);
                } else {
                    $high = '暂无最新出价';
                }
                $v['high'] = $high;

                // 交易方式
                switch ($v['processType']) {
                    case 'INCREMENTAL_BIDDING':
                    case 'REVERSE_BIDDING':
                        $processTypeDesc = '公开竞价';
                        break;
                    case 'GOVERNMENT_REPURCHASE':
                        $processTypeDesc = '政府回购';
                        break;
                    case 'AGREEMENT_TRANSFER':
                        $processTypeDesc = '协议转让';
                        break;
                }
                $v['processTypeDesc'] = $processTypeDesc ? : '';

                // 交易类型
                $v['processCategoryDesc'] = $v['processCategory'] == 'TRANSFER' ? '转让' : '受让';
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * banner列表
     * */
    public function bannerList()
    {
        $input = Request()->param();

        $position = $input['position'] ? : 1;

        $list = Db::name('banner')->field('id,img,type,to_id')->where(['position' => $position])->order('sort asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = $v['img'] ? getHost() . $v['img'] : '';
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 服务分类列表
     * */
    public function serviceTypeList()
    {
        $list = Db::name('service_type')->field('id,name')->order('sort asc')->select();
        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 服务列表
     * */
    public function serviceList()
    {
        $input = Request()->param();

        $type_id = $input['type_id'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['status'] = 1;
        if ($type_id) {
            $type_is_host = Db::name('service_type')->where(['id' => $type_id])->value('is_hot');

            if($type_is_host == 1){
                $where['is_hot'] = $type_is_host;
            }else{
                $where['type_id'] = $type_id;
            }
        }

        $list = Db::name('service')->field('id,name,count,virtual_count,score')->where($where)->order('sort asc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['count'] = number_format($v['count'] + $v['virtual_count']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 服务详情
     * */
    public function serviceDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '服务ID缺失');

        $info = Db::name('service')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['know'] = doEditorContent($info['know']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '服务不存在');
        }
    }

    /**
     * 文章详情
     * */
    public function articleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在');
        }
    }

    /**
     * 认证
     * */
    public function userIdent()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $company_name = $input['company_name'] ? : '';
        $yyzz_img = $input['yyzz_img'] ? : '';
        $username = $input['username'];
        $mobile = $input['mobile'];
        $type = $input['type'] ? : 1;// 1：供应商认证，2：渠道商认证，3：业务员认证

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户不存在');

        if ($type == 1 || $type == 2) {
            if (empty($company_name)) apiReturn(2, '请输入企业名称');
            if (empty($yyzz_img)) apiReturn(2, '请上传营业执照');

            $count = Db::name('user_ident')->where(['company_name' => $company_name, 'type' => $type, 'user_id' => ['neq', $user_id]])->count();
            if ($count > 0) apiReturn(4, '该企业名称已存在');
        }
        if (empty($username)) apiReturn(2, '请输入负责人姓名');
        if (empty($mobile)) apiReturn(2, '请输入联系方式');

        Db::startTrans();
        try {
            $data = [
                'user_id' => $user_id,
                'company_name' => $company_name,
                'yyzz_img' => str_replace(getHost(), '', $yyzz_img),
                'username' => $username,
                'mobile' => $mobile,
                'type' => $type,
                'status' => 0
            ];

            $time = time();
            if ($id) {
                $data['update_time'] = $time;
                $res = Db::name('user_ident')->where(['id' => $id])->update($data);
            } else {
                $data['create_time'] = $time;
                $new_id = Db::name('user_ident')->insertGetId($data);
                $res = (bool)$new_id;
            }

            if ($res) {
                if ($new_id > 0) {
                    $field = '';
                    $user_status = '';
                    switch ($type) {
                        case 1:
                            $field = 'supplier_id';
                            $user_status = 'supplier_status';
                            break;
                        case 2:
                            $field = 'channel_id';
                            $user_status = 'channel_status';
                            break;
                        case 3:
                            $field = 'salesman_id';
                            $user_status = 'salesman_status';
                            break;
                    }
                    if ($field) {
                        $user_update_data = [
                            $field => $new_id,
                            $user_status => 1,
                            'update_time' => $time
                        ];

                        Db::name('user')->where(['id' => $user_id])->update($user_update_data);
                        /**
                         * 情况1：先渠道商认证，再业务员认证 => 如果用户信息渠道商ID已经大于0，且up_channel_user_id等于0的情况下，up_channel_user_id字段绑定$user_id
                         * 情况2：先业务员认证，再渠道商认证 => 如果用户信息业务员ID大于0，且up_channel_user_id等于0的情况下，up_channel_user_id字段绑定$user_id
                         * */
                        if (($type == 3 && $user_info['channel_id'] > 0 && $user_info['up_channel_user_id'] == 0) || ($type == 2 && $user_info['up_channel_user_id'] == 0 && $user_info['salesman_id'] > 0)) {
                            Db::name('user')->where(['id' => $user_id])->setField('up_channel_user_id', $user_id);
                        }
                    } else {
                        Db::rollback();
                        apiReturn(2, '认证失败');
                    }
                }

                Db::commit();
                apiReturn(1, '提交成功');
            } else {
                Db::rollback();
                apiReturn(2, '认证失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '认证失败' . $e->getMessage());
        }

    }

    /**
     * 渠道商发展业务员列表
     * */
    public function userSalesmanList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['u.up_channel_user_id'] = $user_id;
        $where['i.status'] = 1;

        $field = 'u.id,u.avatar,u.username u_username,u.mobile u_mobile,u.son_supplier_count u_count,u.salesman_id,u.create_time u_create_time,i.username i_username,i.mobile i_mobile,i.update_time i_update_time';
        $list = Db::name('user u')->join('user_ident i', 'u.salesman_id = i.id')
            ->field($field)
            ->where($where)
            ->page($page, $pagesize)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = $v['avatar'] ? getHost() . $v['avatar'] : '';
                $v['username'] = $v['i_username'] ? : $v['u_username'];
                $v['mobile'] = $v['i_mobile'] ? : $v['u_mobile'];
                $v['create_time'] = $v['i_update_time'] ? timeFormat($v['i_update_time'], 'Y-m-d') : timeFormat($v['u_create_time'], 'Y-m-d');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 业务员发展供应商列表
     * */
    public function userSupplierList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');


        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['u.up_salesman_user_id'] = $user_id;
        $where['i.status'] = 1;

        $field = 'u.id,u.avatar,u.supplier_company_name,u.username u_username,u.mobile u_mobile,u.supplier_id,u.create_time u_create_time,i.username i_username,i.mobile i_mobile,i.update_time i_update_time,i.company_name';
        $list = Db::name('user u')->join('user_ident i', 'u.supplier_id = i.id')
            ->field($field)
            ->where($where)
            ->page($page, $pagesize)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = $v['avatar'] ? getHost() . $v['avatar'] : '';
                $v['username'] = $v['i_username'] ? : $v['u_username'];
                $v['mobile'] = $v['i_mobile'] ? : $v['u_mobile'];
                $v['create_time'] = $v['i_update_time'] ? timeFormat($v['i_update_time'], 'Y-m-d') : timeFormat($v['u_create_time'], 'Y-m-d');

                $v['company_name'] = $v['supplier_company_name'] ? : '';
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 申请服务
     * */
    public function createOrder()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = openidGetUserId($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '服务ID缺失');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户不存在');

        $info = Db::name('service')->where(['id' => $id])->find();
        if (empty($info)) apiReturn(2, '服务不存在');

        $time = time();
        $data = [
            'order_sn' => 'SV' . date('Ymd') . $user_id . mt_rand(10000, 99999),
            'user_id' => $user_id,
            'service_id' => $id,
            'service_name' => $info['name'],
            'update_time' => $time,
            'create_time' => $time
        ];

        if ($up_salesman_user_id = $user_info['up_salesman_user_id']) {
            $up_channel_user_id = Db::name('user')->where(['id' => $up_salesman_user_id])->value('up_channel_user_id');
            if ($up_channel_user_id) {
                $channel_user_info = Db::name('user')->where(['id' => $up_channel_user_id])->find();
                if ($info['type_id'] && $channel_user_info['channel_is_send_order'] == 1 && $channel_user_info['status'] == 1 && $channel_user_info['channel_type_ids'] && in_array($info['type_id'], explode(',', $channel_user_info['channel_type_ids']))) {
                    // 渠道商认证是否通过
                    if ($channel_id = $channel_user_info['channel_id']) {
                        $status = Db::name('user_ident')->where(['id' => $channel_id])->value('status');
                        if ($status == 1) {
                            // 该服务在渠道商经营范围之类 且 该渠道商认证审核已通过
                            $data['channel_user_id'] = $up_channel_user_id;
                            $data['status'] = 2;
                        }
                    }
                }
            }
        }

        $res = Db::name('order')->insert($data);
        if ($res) {
            apiReturn(1, '申请成功');
        } else {
            apiReturn(2, '申请失败');
        }
    }
}
